﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading.Tasks;

namespace Core.Framework.Common
{
    public static partial class Executer
    {
        public static Task CMDAsync(string fileName, string argument, Func<string, bool> isSuccessFunc, Action<bool> callback)
        {
            var outputTask = Task.Run(() =>
            {
                var output = CMD(fileName, argument);
                var issuccess = isSuccessFunc.Invoke(output);
                callback.Invoke(issuccess);
            });
            return outputTask;
        }
        public static Task<string> CMDAsync(string fileName, string argument)
        {
            var outputTask = Task.Run(() => CMD(fileName, argument));
            return outputTask;
        }




        private static string CMD(string fileName, string argument)
        {
            Process p = new Process();

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                p.StartInfo.FileName = "cmd.exe";
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                p.StartInfo.FileName = fileName;
                p.StartInfo.Arguments = argument;
            }

            p.StartInfo.UseShellExecute = false;    //是否使用操作系统shell启动
            p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
            p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
            p.StartInfo.CreateNoWindow = true;//不显示程序窗口
            p.Start();//启动程序

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                //向cmd窗口发送输入信息
                p.StandardInput.WriteLine(fileName + argument + "&exit");
            }

            p.StandardInput.AutoFlush = true;

            //获取cmd窗口的输出信息
            string output = p.StandardOutput.ReadToEnd();

            Console.WriteLine("output" + output);

            p.WaitForExit();//等待程序执行完退出进程
            p.Close();

            return output;
        }
    }
}
